import json
import asyncio
import requests
from PyQt5.QtCore import QThread, pyqtSignal
from websocket import create_connection

IP = '10.12.59.59'
PORT = '8088'
URL_LOGIN = 'http://%s:%s/login' % (IP, PORT)
URL_CHAT = 'ws://%s:%s/chat' % (IP, PORT)

MSG_TYPE = 'MsgType'
TYPE_SYS = 'system'
TYPE_CHAT = 'chat'


def login(cid, password):
    d = {'cid': cid, 'pw': password}
    # d = {'cid': '1234', 'password': '123'}
    r = requests.post(URL_LOGIN, data=d)
    if r.status_code == 200:
        r = json.loads(r.text)
        if r['result']:
            r.pop('result')
            return True, r
        else:
            return False, r['reason']
    else:
        return False, '服务器出错， code:%s' % r.status_code


class YClient:

    dict_handshake = {'MsgType': 'handshake'}
    dict_chat = {'MsgType': 'chat'}
    CID = 'cid'
    DESID = 'desId'
    TEXT = 'text'

    def __init__(self, ip, port):
        self.URL_CHAT = 'ws://%s:%s/chat' % (ip, port)
        self.ws = create_connection(self.URL_CHAT)
        self.thread = MessageReceiver(self.ws)

    def handshake(self, cid):
        hello = self.dict_handshake.copy()
        hello['cid'] = cid
        self.ws.send(json.dumps(hello))

    def send(self, cid, desId, text):
        info = self.dict_chat.copy()
        info[self.CID] = cid
        info[self.DESID] = desId
        info[self.TEXT] = text
        print(cid, desId, text)
        self.ws.send(json.dumps(info))

    def startReceiveMessage(self, dealMessage):
        self.thread.signal.connect(dealMessage)
        self.thread.start()

    def close(self):
        self.thread.stop = True
        self.ws.close()


class MessageReceiver(QThread):

    stop = False
    signal = pyqtSignal(dict)

    def __init__(self, ws):
        super(MessageReceiver, self).__init__()
        self.ws = ws

    def run(self) -> None:
        while not self.stop:
            r = self.ws.recv()
            print(r)
            try:
                d = json.loads(r)
                self.signal.emit(d)
            except Exception as e:
                print(e)


class MessageCache:

    cache = dict()

    def __init__(self):
        pass

    def append(self, desId, isMine, text):

        desId = str(desId)

        # 如果之前没有聊天记录，则创建一个新的
        if desId not in self.cache.keys():
            self.cache[desId] = list()

        # 根据目标id获取聊天记录列表
        messages = self.cache[desId]

        msg = Message(isMine, text)
        messages.append(msg)

    def getMessages(self, desId):
        if desId in self.cache.keys():
            print('有记录')
            print(self.cache)
            return self.cache[desId]
        else:
            print('没有记录')


class Message:

    message = tuple()

    def __init__(self, isMine, text):
        self.message = (isMine, text)

    def isMine(self):
        return self.message[0]

    def content(self):
        return self.message[1]

    def __repr__(self):
        return '<%s-%s>' % (self.isMine(), self.content())


class YMessage:

    def __init__(self, msg):
        self.msg = msg
        self.msgType = msg[MSG_TYPE]

    def isSys(self):
        return self.msgType == TYPE_SYS

    def isChat(self):
        return self.msgType == TYPE_CHAT

    def getCode(self):
        if self.isSys():
            return self.msg['code']

    def getSrcId(self):
        if self.isChat():
            return self.msg['srcId']

    def getText(self):
        if self.isChat():
            return self.msg['text']